package com.wondream.example.io.nio.socket.simple02;

import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.*;
import java.util.Iterator;

/**
 * @author wangjun
 * @note NioServer
 * @date 2023-11-24  13:19
 */
public class NioServer {
    public static void main(String[] args) throws Exception {
        // 1.得到ServerSocketChannel
        ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();
        // 2.得到Selector
        Selector selector = Selector.open();
        // 3.绑定端口号
        serverSocketChannel.bind(new InetSocketAddress(8888));
        // 4.设置非阻塞
        serverSocketChannel.configureBlocking(false);
        // 5.ServerSocketChannel注册到Selector
        serverSocketChannel.register(selector, SelectionKey.OP_ACCEPT);
        // 6.IO处理
        while (true) {
            // 6.1 监听客户端
            if (selector.select(2000)==0) {
                System.out.println("Server:没有客户端连接，干点别的");
                continue;
            }
            // 6.2 根据selectionKey处理事件
            Iterator<SelectionKey> iterator = selector.selectedKeys().iterator();
            while (iterator.hasNext()) {
                SelectionKey selectionKey = iterator.next();
                if (selectionKey.isAcceptable()) {
                    SocketChannel socketChannel = serverSocketChannel.accept();
                    socketChannel.configureBlocking(false);
                    socketChannel.register(selector, SelectionKey.OP_READ, ByteBuffer.allocate(1024));
                }
                if (selectionKey.isReadable()) {
                    SocketChannel channel = (SocketChannel) selectionKey.channel();
                    Selector selector1 = selectionKey.selector();
                    ByteBuffer buffer = (ByteBuffer) selectionKey.attachment();
                    int readNum = channel.read(buffer);
                    System.out.println(String.format("客户端发来数据：%s", new String(buffer.array(), 0, readNum)));
                }
                if (selectionKey.isWritable()) {

                }
                // 6.3手动从集合中移除当前key，防止重复处理
                iterator.remove();
            }
        }
    }
}
